package com.bw.main

import android.Manifest
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.os.Build
import android.os.Message
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.base.constants.RoutePath
import com.bw.common.adapter.FragmentAdapter
import com.bw.common.entity.CustomEvent
import com.bw.common.view.BaseMvvmActivity
import com.bw.main.databinding.ActivityMainBinding
import com.bw.main.navtab.NavTabItem
import com.bw.main.net.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener
import org.greenrobot.eventbus.EventBus

@Route(path = RoutePath.PATH_MAIN)
@AndroidEntryPoint
class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewModel>() {

    private val fragmentList: ArrayList<Fragment> = arrayListOf()
    private lateinit var fragmentAdapter: FragmentAdapter
    private lateinit var navController: NavigationController


    //需要用户授权项目
    private val needUserPermission = arrayListOf(
        Manifest.permission.INTERNET,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION,
    )

    private val unUserPermission = arrayListOf<String>()
    private var hasUnGranted = false


    override fun initView() {

        binding.vp.offscreenPageLimit = 2

        fragmentList.add(
            ARouter.getInstance().build(RoutePath.PATH_HOME_FRAGMENT).navigation() as Fragment
        )
        fragmentList.add(
            ARouter.getInstance().build(RoutePath.PATH_SERVICE_FRAGMENT).navigation() as Fragment
        )
        fragmentList.add(
            ARouter.getInstance().build(RoutePath.PATH_MESSAGE_FRAGMENT).navigation() as Fragment
        )
        fragmentList.add(
            ARouter.getInstance().build(RoutePath.PATH_CEMENT_FRAGMENT).navigation() as Fragment
        )
        fragmentList.add(
            ARouter.getInstance().build(RoutePath.PATH_MINE_FRAGMENT).navigation() as Fragment
        )



        fragmentAdapter = FragmentAdapter(this, fragmentList)
        binding.vp.adapter = fragmentAdapter



        navController = binding.mainBottomNav.custom()
            .addItem(
                newTabItem(
                    "首页",
                    com.bw.common.R.drawable.tab_home,
                    com.bw.common.R.drawable.tab_home_gray
                )
            )
            .addItem(
                newTabItem(
                    "服务",
                    com.bw.common.R.drawable.tab_service,
                    com.bw.common.R.drawable.tab_service_gory
                )
            )
            .addItem(
                newTabItem(
                    "消息",
                    com.bw.common.R.drawable.tab_message,
                    com.bw.common.R.drawable.tab_message_gory
                )
            )
            .addItem(
                newTabItem(
                    "公告",
                    com.bw.common.R.drawable.tab_cement,
                    com.bw.common.R.drawable.tab_cement_gory
                )
            )
            .addItem(
                newTabItem(
                    "我的",
                    com.bw.common.R.drawable.tab_mine,
                    com.bw.common.R.drawable.tab_mine_gory
                )
            )
            .build()


    }

    override fun initData() {

        //消息和服务
        navController.setHasMessage(2, true)
        navController.setHasMessage(3, true)

        navController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                if (index == 2) {
                    EventBus.getDefault().post(CustomEvent("MessageFragment", "", index))
                }
                binding.vp.currentItem = index
            }

            override fun onRepeat(index: Int) {

            }

        })



        binding.vp.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                navController.setSelect(position)
            }
        })


    }

    override fun handEvent(event: CustomEvent) {
        super.handEvent(event)

        val num = event.data as Int

        navController.setMessageNumber(event.type, num)


    }

    override fun onResume() {
        super.onResume()
        val message = Message.obtain().apply {
            what = 10
            obj = 90
        }
//        mHandle.sendMessageDelayed(message, 2000)

    }

    private fun newTabItem(title: String, cid: Int, did: Int): NavTabItem {
        return NavTabItem(this@MainActivity).apply {
            initData(did, cid, title, false, 0)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //对于用户授权结果进行校验
        if (requestCode == 102 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            unUserPermission.forEach {
                val state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED) {
                    hasUnGranted = true
                }
            }

            if (hasUnGranted) {
                val builder = AlertDialog.Builder(this@MainActivity)
                builder.setTitle("权限提示")
                builder.setMessage("没有授权，请到应用详情中设置")
                builder.setPositiveButton("去设置") { dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                }
                builder.setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                }

                builder.show()

            }


        }
    }

    private fun autoRequestPermission(): Boolean {
        //安卓6.0以上的版本需要发起授权
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            unUserPermission.clear()

            val filter = needUserPermission.filter { s ->
                val state = checkSelfPermission(s)
                state == PackageManager.PERMISSION_DENIED
            }

            unUserPermission.addAll(filter)
            if (unUserPermission.size > 0) {
                requestPermissions(unUserPermission.toTypedArray(), 102)
                return false
            }


        }

        return true

    }

    override fun onDestroy() {
        super.onDestroy()
    }

}